package main

import (
	"fmt"
	"github.com/micro/go-micro/v2"
	"log"
	"runtime"

	"kop/framework/conf"
	"kop/framework/wrapper"
	"kop/libs/database"
	"kop/libs/redis"
	"kop/modules/conquer/handler"
	"kop/modules/conquer/models"
	"kop/modules/conquer/task"
	handler2 "kop/modules/island/handler"
	models2 "kop/modules/island/models"
	"kop/pb/service"
	log2 "kop/util/log"
)

func main() {

	runtime.GOMAXPROCS(2)

	conf.Init()
	log2.SetLevel(conf.Log.Level)

	if err := redis.Init(conf.Redis.Address, conf.Redis.MaxIdle, conf.Redis.MaxActive); err != nil {
		panic(fmt.Errorf("redis error: %w", err))
	}

	database.DB = database.Open(conf.DataBase.Dsn, conf.DataBase.MaxIdle, conf.DataBase.MaxOpen, conf.DataBase.Log)
	defer database.DB.Close()
	models.AutoMigrate(database.DB)
	models2.AutoMigrate()

	go task.Task(database.DB)

	// 消息订阅
	//broker.DefaultBroker = nats.NewBroker()
	//var err = broker.Init(broker.Addrs(strings.Split(conf.Nats.Address, ",")...))
	//if err != nil {
	//	panic(err)
	//}
	//if err = broker.Connect(); err != nil {
	//	panic(err)
	//}

	// New Service
	var srv = micro.NewService(
		micro.Name("go.micro.srv.conquer"),

		micro.WrapHandler(wrapper.NewLogWrapper),
		micro.AfterStart(
			func() error {
				log.Println("启动征服服务器.")
				return nil
			}),
	)

	// Initialise service
	srv.Init()

	// Register Handler
	_ = service.RegisterConquerServiceHandler(srv.Server(), new(handler.ConquerServiceHandler))
	_ = service.RegisterIslandServiceHandler(srv.Server(), new(handler2.IslandServiceHandler))

	// Run service
	if err := srv.Run(); err != nil {
		panic(err)
	}
}
